package com.ruoyi.web.controller.train;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysCommonService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.train.domain.Train;
import com.ruoyi.train.domain.TrainOwnTrainListVo;
import com.ruoyi.train.domain.TrainTotalExportVo;
import com.ruoyi.train.service.ITrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 培训Controller
 *
 * @author zy
 * @date 2022-08-25
 */
@RestController
@RequestMapping("/train")
public class TrainController extends BaseController {

    @Autowired
    private ITrainService trainService;

    @Autowired
    private ISysCommonService sysCommonService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询自身培训列表
     */
    @PreAuthorize("@ss.hasPermi('train:train:list')")
    @GetMapping("/list")
    public TableDataInfo list(Train train) {
        startPage();
        train.setUserId(getUserId());
        List<Train> list = trainService.selectTrainList(train);
        return getDataTable(list);
    }

    /**
     * 获取自身培训详细信息
     */
    @PreAuthorize("@ss.hasPermi('train:train:query')")
    @GetMapping(value = "/{trainId}")
    public AjaxResult getInfo(@PathVariable("trainId") String trainId) {
        Train train = trainService.selectTrainByTrainId(trainId, getUserId());
        if (StringUtils.isNotNull(train)) {
            return AjaxResult.success(train);
        } else {
            return AjaxResult.error("无权限查询他人信息");
        }
    }

    /**
     * 新增培训
     */
    @PreAuthorize("@ss.hasPermi('train:train:add')")
    @Log(title = "培训记录申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Train train) {
        Long userId = getUserId();
        if (Double.parseDouble(train.getTrainHours()) <= 0) {
            return AjaxResult.error("请设置正确的培训时间");
        } else {
            SysUser user = sysUserService.selectUserById(userId);
            //设置userId
            train.setUserId(userId);
            //设置申请人姓名
            train.setUserName(user.getNickName());
            //设置申请人部门
            train.setUserDept(sysCommonService.getDeptNameByUserId(userId));
            //设置人员类别
            train.setUserLeibie(user.getPersonnelCategory());
            //设置人员类型
            train.setUserLeixing(user.getEmployeeType());
            return toAjax(trainService.insertTrain(train));
        }
    }

    /**
     * 查询培训类型/申请人姓名/申请人部门/
     */
    @GetMapping("/queryTrainType")
    public AjaxResult queryTrainType() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("trainType", trainService.queryTrainTypes());
        map.put("deptName", sysCommonService.getDeptName(getDeptId()));
        map.put("nickName", sysCommonService.getUserName(getUserId()));
        return AjaxResult.success(map);
    }

    /**
     * 删除自身培训
     */
    @PreAuthorize("@ss.hasPermi('train:train:remove')")
    @Log(title = "取消培训记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{trainIds}")
    public AjaxResult remove(@PathVariable String[] trainIds) {
        return toAjax(trainService.deleteTrainByTrainIds(trainIds, getUserId()));
    }

    /**
     * 导出自身培训列表
     */
    @PreAuthorize("@ss.hasPermi('train:train:export')")
    @Log(title = "培训记录个人导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Train train) {
        //限定自身数据
        train.setUserId(getUserId());
        List<Train> list = trainService.selectTrainList(train);
        ExcelUtil<Train> util = new ExcelUtil<Train>(Train.class);
        util.exportExcel(response, list, "培训数据");
    }

    /**
     * 指定核实人员获取培训详细信息
     */
    @PreAuthorize("@ss.hasPermi('train:master:query')")
    @GetMapping(value = "/master/{trainId}")
    public AjaxResult masterGetInfo(@PathVariable("trainId") String trainId) {
        Train train = trainService.selectTrainByTrainId(trainId, null);
        if (StringUtils.isNotNull(train)) {
            return AjaxResult.success(train);
        } else {
            return AjaxResult.error("没有该培训流水号的记录");
        }
    }

    /**
     * 指定核实人员、系统管理员查询培训列表
     */
    @PreAuthorize("@ss.hasPermi('train:master:list')")
    @GetMapping("/masterList")
    public TableDataInfo adminList(Train train) {
        startPage();
        List<Train> list = trainService.selectTrainList(train);
        return getDataTable(list);
    }

    /**
     * 指定核实人员审核
     */
    @PreAuthorize("@ss.hasPermi('train:master:approval')")
    @Log(title = "审核培训", businessType = BusinessType.INSERT)
    @PostMapping("/masterApproval")
    public AjaxResult masterApproval(@RequestBody Train train) {
        return AjaxResult.success(trainService.masterApproval(train));
    }

    /**
     * 个人培训查看列表
     */
    @PreAuthorize("@ss.hasPermi('train:admin:ownTrainList')")
    @GetMapping("/ownTrainList")
    public TableDataInfo ownTrainList(Train train) {
        startPage();
        //无姓名搜索条件直接返回
        List<Train> list = trainService.selectTrainByGroup(train);
        return getDataTable(list);
    }

    /**
     * 个人培训Excel详情
     */
    @PreAuthorize("@ss.hasPermi('train:admin:ownExcelInfo')")
    @GetMapping("/ownExcelInfo/{userId}")
    public AjaxResult getOwnExcelInfo(@PathVariable("userId") Long userId) {
        Double traintotal = 0.0;
        HashMap<String, Object> map = new HashMap<>();
        map.put("deptName", sysCommonService.getDeptNameByUserId(userId));
        map.put("nickName", sysCommonService.getUserName(userId));
        map.put("zhiwu", sysCommonService.getUserPositionByUserId(userId));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        map.put("birthday", formatter.format(sysCommonService.getBirthdDay(userId)));
        List<TrainOwnTrainListVo> list = trainService.selectOwnTrainList(userId);
        if (list != null && list.size() > 0) {
            map.put("ExcelList", list);
            for (TrainOwnTrainListVo vo : list) {
                traintotal = traintotal + Double.parseDouble(vo.getTrainHours());
            }
            map.put("traintotal", traintotal);
        }
        return AjaxResult.success(map);
    }

    /**
     * 导出所有培训记录统计
     */
    @PreAuthorize("@ss.hasPermi('train:admin:exportAll')")
    @Log(title = "管理员导出所有培训记录统计", businessType = BusinessType.EXPORT)
    @PostMapping("/adminExportAll")
    public void adminExportAll(HttpServletResponse response, Train train) {
        List<TrainTotalExportVo> list = trainService.selectListAll();
        ExcelUtil<TrainTotalExportVo> util = new ExcelUtil<TrainTotalExportVo>(TrainTotalExportVo.class);
        util.exportExcel(response, list, "培训数据");
    }

    /**
     * 导出所选项（trainId）
     */
    @PreAuthorize("@ss.hasPermi('train:admin:export')")
    @Log(title = "管理员导出所选培训记录统计", businessType = BusinessType.EXPORT)
    @PostMapping("/adminExport")
    @ResponseBody
    public AjaxResult adminExport(HttpServletRequest request, HttpServletResponse response, @RequestBody String[] ids) {
        if (ids == null || ids.length == 0) {
            return AjaxResult.error("未选择数据");
        } else {
            List<TrainTotalExportVo> objects = trainService.selectList(ids);
            ExcelUtil<TrainTotalExportVo> util = new ExcelUtil<TrainTotalExportVo>(TrainTotalExportVo.class);
            return util.exportExcel(objects, "培训数据");
        }
    }

    /**
     * 培训记录统计筛选列表
     */
    @PreAuthorize("@ss.hasPermi('train:admin:list')")
    @GetMapping("/listByAdmin")
    public TableDataInfo listByDept(Train train) {
        startPage();
        List<Train> list = trainService.selectTrainList(train);
        return getDataTable(list);
    }

    /**
     * 下拉菜单，部门 / 人员类型 / 岗位类别 数据
     */

    @GetMapping("/getDept")
    public AjaxResult getDept() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("deptList", trainService.getDept());
        map.put("roleName", sysCommonService.getRoleName());
        map.put("postName", sysCommonService.selectPositionType());
        return AjaxResult.success(map);
    }
}
